package com.example.nonacademic_education.service.impl;

import com.example.nonacademic_education.dao.AnyConstantDao;
import com.example.nonacademic_education.dao.AuthorityDao;
import com.example.nonacademic_education.data.response.AuthorityDto;
import com.example.nonacademic_education.entity.AnyConstant;
import com.example.nonacademic_education.service.AnyConstantService;
import com.example.nonacademic_education.util.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AnyConstantServiceImpl implements AnyConstantService {
    @Resource
    private AnyConstantDao anyConstantDao;
    @Resource
    private AuthorityDao authorityDao;

    @Override
    public R getList() {
        Map<String,Object> data = new HashMap<>();
        data.put("list",anyConstantDao.getList());
        data.put("total",anyConstantDao.count());
        return R.ok(data,"查询成功");
    }

    @Override
    public R updateOne(AnyConstant anyConstant) {
        anyConstantDao.updateOne(anyConstant);
        return R.ok("修改成功");
    }

    @Override
    public R getAuthorityValue(Long id) {
        String value=anyConstantDao.getValueById(id);
        String[] split = value.split(",");
        List<Long> authorities=new ArrayList<>();
        for (String s : split) {
            authorities.add(Long.parseLong(s));
        }
        Map<String, Object> data = new HashMap<>();
        List<AuthorityDto> list=authorityDao.getAll(0L);
        for (AuthorityDto authorityDto : list) {
            authorityDto.setChildren(authorityDao.getAll(authorityDto.getId()));
            for (int j = 0; j < authorityDto.getChildren().size(); j++) {
                if (authorities.contains(authorityDto.getChildren().get(j).getId())){
                    authorityDto.getChildren().get(j).setIsGranted(1);
                }else {
                    authorityDto.getChildren().get(j).setIsGranted(0);
                }
            }
        }
        data.put("list",list);
        return R.ok(data, "getAll");
    }
}
